package edu.seu.mart.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import edu.seu.mart.model.*;
import edu.seu.mart.service.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;

/**
 * Created by Administrator on 2015/3/11.
 */
@Controller
@RequestMapping("/order")
public class OrderController {

    @Resource
    private IOrderService orderService;

    @Resource
    private IAddressService addressService;

    @Resource
    private IOrderItemService orderItemService;

    @Resource
    private ISellerService sellerService;

    @Resource
    private IUserService userService;

    @Resource
    private IGoodsService goodsService;

    @Resource
    private ICartService cartService;


    @RequestMapping(value = "/{id}/orderDelete", method = RequestMethod.GET)
    public String orderDelete(@PathVariable int id) {
        orderItemService.deleteOrderId(id);
        orderService.delete(id);
        return "redirect:/order/orders";
    }

    @RequestMapping(value = "/orders")
    public String orders(Model model, HttpServletRequest req, HttpSession session) {
        String state = req.getParameter("state");
        User user = (User) session.getAttribute("loginUser");
        if (user == null) {
            return "redirect:/user/login";
        }
        if (state == null) {
            model.addAttribute("orders", orderService.loadByUserId(user.getId()));
        } else {
            model.addAttribute("orders", orderService.findByUserState(user.getId(), state));
        }
        return "user/orders";
    }

    /**
     * 用户地址管理
     */
    @RequestMapping(value = "/addUserAddress", method = RequestMethod.GET)
    public String addressAdd(Model model, HttpSession session) {
        User user = (User) session.getAttribute("loginUser");
        if (user == null) {
            return "redirect:/user/login";
        }
        model.addAttribute("addresses", addressService.loadUserAdresss(user.getId()));
        model.addAttribute(new Address());
        return "user/addUserAddress1";
    }

    @RequestMapping(value = "/addUserAddress", method = RequestMethod.POST)
    public String addressAdd(@Validated Address addr, BindingResult br, Model model, HttpSession session) {
        User user = (User) session.getAttribute("loginUser");
        if (user == null) {
            return "redirect:/user/login";
        }
        ModelMap mmap = new ModelMap();
        addr.setUser_id(user.getId());
        addressService.add(addr);
        return "redirect:/cart/userCartList";
    }

    @RequestMapping(value = "/{id}/deleteAddress", method = RequestMethod.GET)
    public String deleteAddress(@PathVariable int id) {
        addressService.delete(id);
        return "redirect:/order/add";
    }

    /**
     * 新增订单
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public void add(@RequestParam String cartjson, HttpServletResponse resp) throws IOException {
        JSONObject object = JSON.parseObject(cartjson);
        int addressId = (int) object.get("address");
        Address address = addressService.findAddressById(addressId);
        List<Map<String, Object>> list = (List<Map<String, Object>>) object.get("carts");
        List<Integer> cartids = new ArrayList<Integer>();
        for (Map<String, Object> obj : list) {
            int sellerId = (int) obj.get("seller_id");
            int userId = (int) obj.get("user_id");
            double total = 0;
            Order order = new Order();
            order.setSeller_id(sellerId);
            order.setAddress(address);
            order.setOrderdate(new Date());
            order.setState("待付款");
            order.setUser_id(userId);
            List<Map<String, Object>> sublist = (List<Map<String, Object>>) obj.get("goods");
            Set<OrderItem> orderItems = new HashSet<>();
            for (Map<String, Object> goods : sublist) {
                Integer quantity = (Integer) goods.get("quantity");
                Integer goodsId = (Integer) goods.get("id");
                Goods goods1 = goodsService.load(goodsId);
                goods1.setStock(goods1.getStock() - quantity);
                goodsService.update(goods1);
                Double subtotal = Double.parseDouble(goods.get("subtotal").toString());
                Integer cartid = (Integer) goods.get("cartid");
                cartids.add(cartid);
                total += subtotal;
                OrderItem orderItem = new OrderItem();
                orderItem.setQuantity(quantity);
                orderItem.setGoods(goodsService.load(goodsId));
                orderItem.setSubtotal(subtotal);
                orderItems.add(orderItem);
                orderItemService.add(orderItem);
            }
            order.setOrderItems(orderItems);
            order.setTotal(total);
            orderService.add(order);
        }
        System.out.println("订单生成成功！");
        /**
         * 订单生成成功后删除购物车记录
         */
        if (cartids.get(0) != -1) {
            cartService.delete(cartids);
        }
        resp.getWriter().print("sucess");
    }


    @RequestMapping(value = "/{id}/orderDetail", method = RequestMethod.GET)
    public String orderDetail(@PathVariable int id, Model model) {
        Order order = orderService.load(id);
        model.addAttribute("order", order);
        model.addAttribute("seller", sellerService.load(order.getSeller_id()));
        return "user/orderDetail";
    }

    @RequestMapping(value = "/{orderId}/pay", method = RequestMethod.GET)
    public String pay(@PathVariable int orderId, HttpSession session, Model model) {
        User user = (User) session.getAttribute("loginUser");
        if (user == null) {
            return "redirect:/user/login";
        }
        double userMoney = user.getMoney();
        Order order = orderService.load(orderId);
        String state = order.getState();
        switch (state) {
            case "待付款":
                if (userMoney < order.getTotal()) {
                    throw new MartException("用户余额不足！");
                } else {
                    userService.updateMoney(user.getId(), (userMoney - order.getTotal()));
                    orderService.updateState(orderId, "待发货");
                    return "user/paySuc";
                }
            case "待发货":
                throw new MartException("提醒成功");
            case "待收货":
                System.out.println("待收货");
                Seller seller = sellerService.load(order.getSeller_id());
                sellerService.updateMoney(seller.getId(), (seller.getMoney() + order.getTotal()));
                orderService.updateState(orderId, "已完成");
                System.out.println("123:" + orderService.load(orderId).getState());
                return "redirect:/order/orders";
            case "已完成":
                Set<OrderItem> orderItems = order.getOrderItems();
                List<OrderItem> List = new ArrayList<OrderItem>();
                for (OrderItem item : orderItems) {
                    List.add(item);
                }
                model.addAttribute("order", List);
                model.addAttribute("orderId", order.getId());
                return "user/comment";
            default:
                return "redirect:/order/orders";
        }
    }

    @RequestMapping(value = "{id}/orderBack", method = RequestMethod.GET)
    public String back(@PathVariable int id) {
        orderService.updateState(id, "退款中...");
        return "redirect:/order/orders";
    }
}
